var tawags=null;
(function(w){

    w.fn.wJabber = function(options) {
        var $this=w(this);
        //alert("w($this).text(): "+w($this).text());
        //var calls = multiCallContainer('call', 'calllist');
        
        var ws = w.extend({
            _callcontainer:"#callcontainer",
            $callcontainer:null,
            _calllist:"#calllist",
            _parentId:"calllist", //  Must same value to  _calllist
            _participant: 6969,
            _phoneRegistered:null,
            _videoObject: null
            
        }, options );
        var $callcontainer = null;
        var $phonecontainer = null;
        var $cwicAbout = null; // Not sure is this already available
        
        
        var delayedVideoConversation = null;        
        var settings = {
            log: function (msg, context) {
                //console.trace();
                if (typeof console !== "undefined" && console.log) {         
                    console.log(msg);
                    if (context) {
                        if(console.dir){
                            console.log(context);
                        } else if(typeof JSON !== "undefined" && JSON.stringify) {
                            console.log(JSON.stringify(context,null,2));
                        } else {
                            console.log(context);
                        }
                    }
                };
            }
        };
        
        var callPrefix = "call";
        var calllists = {},
            selectedCallId=null;
         
        console.log("wJabber Start");
        var methods = {
            setParticipant: function(__participant){
              ws._participant = __participant;
              return this;
            },
                    
            setCalls: function(calls){
              //calls =
            },
            isPhoneRegistered: function(){
                return ws._phoneRegistered;
            },
            setPhoneRegistered:  function(phoneRegistered){
              ws._phoneRegistered =phoneRegistered;
              return this;
            },
                  
            phoneReadyCallback:  function(defaults,phoneRegistered, phoneMode) {
                
                // Initialize elements
                console.log("=============>@phoneReadyCallback START");
                console.log("=============>@phoneReadyCallback phoneMode:"+phoneMode);
                console.log("=============>@phoneReadyCallback defaults:"+defaults);
                //alert("Start phoneReadyCallback");
                $phonecontainer=$this;//w('#phonecontainer');
                $cwicAbout = $this.cwic('about');
                $callcontainer = w(ws._callcontainer);
//                if ($cwicAbout.capabilities.video){
//                    
//                    if ($cwicAbout.capabilities.videoPluginObject){
//                        alert("Video Capabilities Plugin Object");
//                    }
//                }
                
                // Create Video Window
                
                //console.log("==========> #remotevideocontainer -> Create Video Object");
                //// Move On the time the DOM Element created
                this.createVideoWindow('videoobject');
                //console.log("==========> #remotevideocontainer -> DONE Creating Video object");
                if(!phoneRegistered) {
                    $this.cwic('disableCertValidation');//$phonecontainer.cwic('disableCertValidation');
                    methods.login($this); //methods.login($phonecontainer);
                }else{
//                    console.log('Winz -> registered in mode ' + phoneRegistered.mode);
//                    console.log("Winz -> registered device "+phoneRegistered.device.name);
                    //methods.call();
                    // Call
                    ws._phoneRegistered = phoneRegistered;
                }
                
            },
            /**
             * 
             * @param {type} err -> error object
             * @param {type} exc -> ecexption Object
             */
            phoneErrorCallback: function(err, exc) {
                if (err) {
                    var EXT_MISSING_CODE = 42;
                    settings.log('phone error: ', err);
                    var msg = 'ERROR: cannot initialize phone: ' + err.message + ' (code ' + err.code + ')<br>';

                    if(err.code == EXT_MISSING_CODE){
                        msg += '\nChrome extension available at <a href="https://chrome.google.com/webstore/detail/cisco-web-communicator/ppbllmlcmhfnfflbkbinnhacecaankdh/" target="_blank" style="color:blue">chrome web store</a>.';
                    }
                    w('#msgcontainer').empty().html('<b style="color:red">' + msg + '</b>');

                    //var about = w().cwic('about');
                   //showVersions(about);
                }

                if (exception) {
                    settings.log('exception: ',exception);
                }
            },
            /**
             * 
             * @param {str} u - Username
             * @param {str} p - password
             * @param {str} h - host
             */
            login:function(u, p, h){
                // Login here. Please create method for this one
                //$phonecontainer.cwic('registerPhone', {
                $this.cwic('registerPhone', {
                    user: 'winzter143',
                    password: 'fatbox123',
                    cucm: '192.168.101.8',
                    mode: 'SoftPhone',
                    authenticate: "false", //auth,
                    forceRegistration: "true", //forcereg,
                    devicesAvailable: function(devices,phoneMode,callback,automatic) {
                        console.log("Connect to ECPDemo");
                        callback("SoftPhone", "ECPDemo","");
                    },
                    success: function(reg) {
                        console.log('======>>>>registered in mode ' + reg.mode+" with device "+reg.device.name);
                        //methods.call(reg);
                        ws._phoneRegistered = reg;
                    },
                    error:methods.handleLoginFailure
                }); // End of registerPhone
                return this;
            },
            logout: function (){
                //$phonecontainer.cwic('unregisterPhone', {
                $this.cwic('unregisterPhone', {
                    forceLogout: true,
                    // the complete callback is always called after unregistering
                    complete: function(){
                        for(var call in calllists) {
                            if(calllists.hasOwnProperty(call)) {
                                methods.removeCall(calllists[call].id);
                            }
                        }
                    }
                });
                return this;
            },
            /*
             * Remove All registered call. Incomming/ 
             */
            handleLoggedOut: function (){
                //ca$thislls.removeAll();
            },
            call:function(reg){
                console.log("======>>>>>>>> Call the user: "+ws._participant);
                var videodirection = true;
                if (this.isPhoneRegistered()){
                    var originateObject = {
                        participant: {recipient: ws._participant}, // Syntax-pc
                        //videoDirection: (videodirection?'SendRecv':($cwicAbout.capabilities.video?'RecvOnly':'Inactive')),
                        videoDirection: ($this.cwic('about').capabilities.video?'SendRecv':'RecvOnly'),
                        remoteVideoWindow: 'videocallobject'};
                    //console.log("Before Call Video Object");
                    //$phonecontainer.cwic('startConversation',originateObject);
                    $this.cwic('startConversation',originateObject);
                    //w("#phonecontainer").cwic('startConversation',originateObject);
                    console.log("ZEnd Call Video Object");
                }else{
                    // TODO - Suunds like I need to register the phone again.
                    console.log('Phone is not register yet. Try again in few seconds');
                    return false;
                }
                return this;
            },
                    
            endCall:function (){
                console.log("endtawag calls");
                methods.getCallDiv().cwic('endConversation');
                return this;
            },
            addCall: function(conversation, container) {
                var callIsNew = false;
                console.log("Start addCall: "+conversation.callId);
                if(!(calllists[conversation.callId])) {
                    
                    // no call or old call is not connected or not (Ringout || OffHook && canEndCall) and new one is something more active
                    // entirely too complicated of a condition, but that's asynchronous multiple calls for you
                    if(!selectedCallId || !calllists[selectedCallId] || (calllists[selectedCallId].callState !== "Ringout" && calllists[selectedCallId].callState !== 'Connected' && (calllists[selectedCallId].callState !== 'OffHook' || !calllists[selectedCallId].capabilities.canEndCall) && (conversation.callState === 'Ringin' || conversation.callState === 'Ringout'||conversation.callState === 'OffHook'))) {
                        selectedCallId = conversation.callId;
                        //$('ul#calllist li').removeClass('selected');
                    }
                    //console.log("===========>>> \n\n\tparentId"+ws._parentId);
                    var $calls = $('#' + ws._parentId);
                    $calls.append($('<li' +(selectedCallId === conversation.callId ? ' class="selected"' : '') + ' id="' + callPrefix + '_' + conversation.callId + '"><span class="controls"><button type="button" class="answerbtn">Answer</button> <button type="button" class="divertbtn">iDivert</button></span><span class="name"></span><span class="state"></span>'));//<b>' + conversation.participant.name + ':</b> ' + conversation.participant.recipient + '</li>'));
                    $calls.addClass('.cwic-conversation-' + conversation.callId);
                    //$calls[0].scrollTop = $calls[0].scrollHeight;

                    $newCall = $('#'+callPrefix+'_'+conversation.callId);
    //                $newCall.find('.answerbtn').click(incomingAnswerClick);
    //                $newCall.find('.divertbtn').click(incomingDivertClick);
                    $newCall.bind('conversationUpdate.cwic',methods.handleConversationUpdate)
                            .bind('conversationEnd.cwic', methods.handleConversationEnd);
                    callIsNew = true;
                    //$('#switchmodebtn').attr('disabled',true);
                }
                calllists[conversation.callId] = conversation;
                methods.updateCall(conversation, container);
                return callIsNew;
            },
            updateCall: function(conversation,container) {
                console.log("====>>>>>>> start updateCall("+callPrefix+"_"+conversation.callId+")");
                var $update = w('#' + callPrefix + '_' + conversation.callId);
                var name = '';
                var number='';
                var title = '';
                var state = '';
                if(container) {
                    var $container = w(container);
                    var classes = methods.getCwicClasses($container);
                    var oldclasses = methods.getCwicClasses($update);
                    $container.removeClass(classes);
                    $update.data('cwic',$container.data('cwic')).removeClass(oldclasses).addClass(classes);
                }
                if(conversation.callState === 'Reorder') {
                    name = conversation.calledPartyNumber;
                    state = 'Call Failed';
                } else {
                    state = conversation.callState;
                    // @win -> No conference feature
                    //if (conversation.isConference) {
                    //    name = 'Conference';
                    //    for(var i=0;i<conversation.participants.length;i++) {
                    //        title += (i>0 ? ', ' : '') + conversation.participants.name;
                    //    }
                    //}
                    if (conversation.callType === "Outgoing") {
                        name = conversation.calledPartyName;
                        number = conversation.calledPartyNumber;
                        title = conversation.calledPartyDirectoryNumber;
                    }
                    // Furely out going only
                    else if (conversation.callType === "Incoming") {
                        name = conversation.callingPartyName;
                        number = conversation.callingPartyNumber;
                        title = conversation.callingPartyDirectoryNumber;
                    }
                }
                //if(conversation.capabilities.canImmediateDivert || conversation.capabilities.canAnswerCall) {
                //    $update.find('.divertbtn').attr('disabled', !conversation.capabilities.canImmediateDivert);
                //    $update.find('.answerbtn').attr('disabled', !conversation.capabilities.canAnswerCall);
                //    $update.find('.controls').show();
                //} else {
                //    $update.find('.controls').hide();
                //}
                
                if(conversation.callState === "Connected"){
                    //$callcontainer.css('display','inline-block');
                    w('#videocontainer').css('display','inline-block');
                    w('#videocontainer').find('.remotename').text(((number === '') ? '' : number + ' - ') + name).attr('title',title);
                    w('#videocontainer').find('.state').text(state).attr('class', 'state ' + conversation.callState);    
                    // TODO: Start timer for the Call
                }
                
                w("#state").text(conversation.callState).addClass('class', 'state ' + conversation.callState);
                if(!selectedCallId) {
                    methods.setSelectedCall(conversation.callId);
                }
            },
            removeCall: function(callid) {
                if(calllists[callid]) {
                    delete calllists[callid];
                    console.log("==============>>>>>>>>DELETE -----  "+callPrefix + '_' + callid);
                    var $remove = w('#' + callPrefix + '_' + callid);
                    // Unbind and related button
                    $remove.find('.answerbtn').unbind();
                    $remove.find('.divertbtn').unbind();
                    $remove.unbind().remove();
                }else{
                    console.log("==============>>>>>>>>NO ITEM TO DELETE -----  "+callPrefix + '_' + callid);
                }
                selectedCallId = null;
                for(var call in calllists) {
                    if(calllists.hasOwnProperty(call)) {
                        selectedCallId = calllists[call].id;
                    }
                }
                methods.setSelectedCall(selectedCallId);
                if(!selectedCallId) {
                    //$('#switchmodebtn').removeAttr('disabled');
                    //$('#callcontainer').hide();
                    //$callcontainer.find('.callinfo').text("");
                    //if(popupwindow) {popupwindow.close();}
                }
            },
        
            handleLoginFailure: function(err){
                var msg = 'Unable to login: ' + err.message+' ';
                    msg += err.details.join(', ');
                //$('#msgcontainer').html(msg);
                //w("#phonecontainer").cwic('unregisterPhone',{forceLogout:true});
                $this.cwic('unregisterPhone',{forceLogout:true});
                
                // I must able to check what kind off error
                // Loggin?
                // Phone Connect?
                
            },
            handleConversationIncoming:function (event, conversation, containerdiv) {
                console.log("start handleConversationIncoming");
                //calls.addCall(conversation, containerdiv);
            },
            handleConversationStart:function (event, conversation, containerdiv) {
                //settings.log("start handleConversationStart("+event+", "+conversation+", "+containerdiv+")");
                methods.addCall(conversation, containerdiv);
                methods.updateConversationInfo(conversation, ws._callcontainer);
            },
            handleConversationUpdate: function (event, conversation, container) {
                console.log("============>>>> handleConversationUpdate <<<==============");
                settings.log('=======>>> conversationUpdate Event for conversation:'+conversation.callId+' on Dom node: ' + event.target.id, conversation);
                methods.addCall(conversation, container);
                methods.updateConversationInfo(conversation, container);
            },
            handleConversationEnd: function(event, conversation) {
                console.log("============>>>> handleConversationEnd <<<==============");
                //$callcontainer.hide();
                //w("#videocontainer").css('display','inline-block');
                w("#videocontainer, .videocontainer").hide();
                // TODO - Stop teh timer
                methods.removeCall(conversation.callId);
                
                // Return to Welcome page and Hide Video
                jQuery("#videocontainer").hide();
                jQuery(".videocontainer").hide();
                gwd.actions.gwdPagedeck.goToPage('pagedeck', 'welcome', 'fade', 500, 'ease-in-out', 'top');

                settings.log('conversationEnd Event for conversation:'+conversation.callId);
                console.log('=========>>>>>>>>conversationEnd Event for conversation:'+conversation.callId);
                delayedVideoConversation = null;
                if (methods.isCallListEmpty()){
                    //methods.removeExternalVideoTitle();
                    //w(document).cwic('setExternalWindowTitle', "");
                    //w(document).cwic('hideExternalWindow');
                    //$('#closeexternalwindow').attr('disabled', false);
                    //$('#externalpreview').attr('disabled', false);
                } else {
                    //methods.setExternalVideolTitle();
                    //w(document).cwic('setExternalWindowTitle', "Winzter Calling");//methods.generateExternalVideoTitleString() );
                }
            },

            /**
             * 
             * @param {type} conversation
             * @param {type} callcontainer -> the DIV for video container
             * @returns {unresolved}
             */
            updateConversationInfo:function (conversation, callcontainer){
                console.log("===========>>>>> updateConversationInfo start");
                if(!methods.getSelectedCall() 
                    || methods.getSelectedCall().callId !== conversation.callId) {
                    // special case where hold shows up for previous call after the current call is answered if the
                    // previous call was in process when the user clicked answer to a new incoming call.
                    // Remove the video window so it blanks out correctly
                    if (conversation && conversation.callState 
                            && ((conversation.callState=== 'Hold' || conversation.callState==='RemHold'))) {
                        settings.log("Hold received for non-current call, checking for video");
                        if (ws._videoObject) {
                           // console.log("===========>>>>> updateConversationInfo Update Video Object");
                            //settings.log("Hold received for non-current call, removing video conversation.callId: " + conversation.callId);
                            methods.getCallDiv(conversation.callId).cwic('updateConversation',{'removeRemoteVideoWindow':ws._videoObject});
                        }
                    }
                    else {
                        //settings.log("updateConversationInfo() event not for current call, ignoring");
                    }

                    return;
                }
                //var $callcontainer = w(callcontainer);
                //methods.updateTransferConferenceLists(conversation);
                //$callcontainer.css('display','inline-block');
                if(conversation.isConference) {
                    //$callcontainer.find('.remotename').text("Conference");
                }
                else if(conversation.callType === "Outgoing") {
                    settings.log("Outgoing Call");
                    //$callcontainer.find('.remotename').text(conversation.calledPartyDirectoryNumber + ((conversation.participant.name === "") ? "" : " - " + conversation.participant.name));
                }
                //else if (conversation.callType === "Incoming") {
                    //$callcontainer.find('.remotename').text(conversation.callingPartyDirectoryNumber + ((conversation.participant.name === "") ? "" : " - " + conversation.participant.name));
                //}
                //$callcontainer.find('.callinfo').text(conversation.callState);
                if (conversation.callState==='Busy') {
                    // Busy
                    //Return to home
                    console.log("Number is busy...");
                    tawags.endCall();
                    gwd.actions.gwdPagedeck.goToPage('pagedeck', 'welcome', 'fade', 500, 'ease-in-out', 'top');
                    jQuery("#videocontainer").hide();
                    jQuery(".videocontainer").hide();

                }
                
                if (conversation.callState==='Hold' || conversation.callState==='RemHold') {
                    // In some cases, if the video window is not removed on hold, it cannot be re-added
                    // on resume.
                    // remove the video window from a call on hold to blank out the video window
                    // and to allow the video to be re-added properly when the call is resumed later

                    //settings.log("Hold received, removing video");
                    //$callcontainer.find('.holdresumebtn').attr('disabled', !conversation.capabilities.canResume).text('Resume').addClass('held');
                    if (ws._videoObject) {
                        methods.getCallDiv().cwic('updateConversation',{'removeRemoteVideoWindow':ws._videoObject});
                    }
                } else {
                    //$callcontainer.find('.holdresumebtn').attr('disabled', !conversation.capabilities.canHold).text('Hold').removeClass('held');
                }
                //$callcontainer.find('.endbtn').attr('disabled', !conversation.capabilities.canEndCall);

                if (conversation.state === 'Reorder') {
                    alert("Call failed");
                    //$callcontainer.find('.callinfo').text('Call failed');
                }

                if (conversation && conversation.callState === "Connected" && (conversation.videoDirection === "RecvOnly" || conversation.videoDirection === "SendRecv")) {
                    console.log("=>>>>Conversion Connected!!!!!!");

                    if (conversation.callEvent==='evCallStarted' || conversation.callEvent==='evVideoAvailable'){
                        console.log("Conversion showCallInExternalWindow");
                        // I dont want to open external window to show
                        //methods.getCallDiv().cwic('showCallInExternalWindow'); 
                        //methods.setExternalVideolTitle();
                    }

                    if(ws._videoObject) {
                        console.log("#############################################################################");
                        console.log(" =====>>>>>VideoObject call {updateConversation}: "+methods.getCallDiv().attr("id")+" : "+methods.getCallDiv().attr("class"));
                        w("#videocontainer, .videocontainer").show();
                        methods.getCallDiv().cwic('updateConversation',{'addRemoteVideoWindow':ws._videoObject});
                    }
                    else {
                        // The update for the conversation that video is ready can occur before the createVideoWindow() call  
                        // returns asynchronously on some browsers, especially on Safari and background tabs.  Save off the 
                        // conversation so that we can add the window to it when it is ready.
                        delayedVideoConversation = conversation;
                        console.log("Delayed Video Conversation???");
                    }
                    // @win -> Since no popup Comment out this one then
                    //if(popupwindow && !popupwindow.closed && popupwindow.videoObject) {
                    //    console.log("");
                    //    calllists.getCallDiv().cwic('updateConversation',{'addRemoteVideoWindow':popupwindow.videoObject,window:popupwindow});
                    //}
                }
                if(conversation.audioMuted) {
                    //$callcontainer.find('.muteaudiobtn').attr('disabled', !conversation.capabilities.canUnmuteAudio);
                    //$callcontainer.find('.muteaudiobtn').text('Unmute Audio').addClass('muted');
                } else {
                    //$callcontainer.find('.muteaudiobtn').attr('disabled', !conversation.capabilities.canMuteAudio);
                    //$callcontainer.find('.muteaudiobtn').text('Mute Audio').removeClass('muted');
                }

                if(conversation.videoMuted) {
                    //$callcontainer.find('.mutevideobtn').attr('disabled', !conversation.capabilities.canUnmuteVideo);
                    //$callcontainer.find('.mutevideobtn').text('Unmute Video').addClass('muted');
                } else {
                    //$callcontainer.find('.mutevideobtn').attr('disabled', !conversation.capabilities.canMuteVideo);
                    //$callcontainer.find('.mutevideobtn').text('Mute Video').removeClass('muted');
                    //calllists.setExternalVideolTitle();
                }

                if(conversation.videoDirection==="Inactive" || conversation.videoDirection==="RecvOnly/") {
                    //$callcontainer.find('.escalatebtn').text('Escalate').attr('disabled',!conversation.capabilities.canUpdateVideoCapability);
                } else {
                    //$callcontainer.find('.escalatebtn').text('De-escalate').attr('disabled',!conversation.capabilities.canUpdateVideoCapability);
                }


            },// function updateConversationInfo(conversation, callcontainer){

            updateTransferConferenceLists: function(conversation) {
                console.log("Start updateTransferConferenceLists - sounds not use to this project");
                var existingCalls = methods.getCalls();
                var text = '';
                //w('#conferencelist').empty();
                //w('#transferlist').empty();
                var conferenceAvailable = false;
                var transferAvailable = false;
                if(conversation && conversation.callState === "Connected") {
                    for(var call in existingCalls) {
                        if(existingCalls.hasOwnProperty(call)) {
                            if(conversation.capabilities.canJoinAcrossLine && existingCalls[call].callId !== conversation.callId && existingCalls[call].capabilities.canJoinAcrossLine) {
                                if(existingCalls[call].isConference) {
                                    text = "Conference";
                                } else if(existingCalls[call].callType === "Outgoing") {
                                    text=existingCalls[call].calledPartyDirectoryNumber;
                                } else {
                                    text=existingCalls[call].callingPartyDirectoryNumber;
                                }
                                //$('#conferencelist').append("<option value='" + existingCalls[call].callId + "'>" + text + "</option>");
                                conferenceAvailable = true;
                            }
                            if(conversation.capabilities.canDirectTransfer && existingCalls[call].callId !== conversation.callId && existingCalls[call].capabilities.canDirectTransfer) {
                                if(existingCalls[call].isConference) {
                                    text = "Conference";
                                } else if(existingCalls[call].callType === "Outgoing") {
                                    text=existingCalls[call].calledPartyDirectoryNumber;
                                } else {
                                    text=existingCalls[call].callingPartyDirectoryNumber;
                                }
                                //$('#transferlist').append("<option value='" + existingCalls[call].callId + "'>" + text + "</option>");
                                transferAvailable = true;
                            }
                        }
                    }
                }
                //$('#conferencebtn').attr('disabled', !conferenceAvailable);
                //$('#transferbtn').attr('disabled', !transferAvailable);
            },

            getCwicClasses: function(el) {
                var classes = w(el).attr('class');
                console.log("Start getCwicClasses: ("+classes+ ")");
                var classestoadd = [];
                if(classes) {
                    classes = classes.split(' ');
                    for(var i=0;i<classes.length;i++) {
                        if(classes[i].substring(4,0) === 'cwic') {
                            classestoadd.push(classes[i]);
                        }
                    }
                }
                return classestoadd.join(' ');
            },
            getCallDiv: function(callId) { // from Helper
                //console.log("Start getCallDiv");
                if(!callId) {
                    callId = selectedCallId;
                }
                var callDiv = callPrefix+'_'+callId;
                console.log("========>>> getCallDiv: "+callDiv);
                return w('#'+callDiv);
            },
            getSelectedCall: function() {
                return calllists[selectedCallId];
            },
            getCalls: function(){return calllists;},       
            setSelectedCall: function(callid) { // from Helper
                selectedCallId = callid;
                //w('#calllist li').removeClass('selected');
                //w('#'+callPrefix+'_'+callid).addClass('selected');
                //$callcontainer = w(ws._callcontainer);
                methods.updateConversationInfo(calllists[selectedCallId], $callcontainer);
            },

            isCallListEmpty:function(){ // from Helper
                
                //if (w(ws._calllist).children().size()) {
                //    return false;
                //}
                return true;
            },
            
            generateExternalVideoTitleString: function () { // from Helper
                var selectedCall = methods.getSelectedCall();
                var otherPartyName = selectedCall.participant.name;
                var otherPartyNumber = selectedCall.participant.number;
                var callHeldInfo = ((selectedCall.callState === "Hold") ? "\t- on hold" : "");

                var externalVideoTitle = otherPartyNumber + ((otherPartyName === "") ? "" : " - " + otherPartyName) + callHeldInfo;
                return externalVideoTitle;
            },

            setExternalVideolTitle: function () {
                w(document).cwic('setExternalWindowTitle',"Winzter: "+methods.generateExternalVideoTitleString());
            },

            removeExternalVideoTitle: function () {
                w(document).cwic('setExternalWindowTitle', "");
            },

            __init: function(){
                    console.log($this.attr("id")+":"+$this.attr("id"));
                    $this.bind('conversationStart.cwic', this.handleConversationStart)
                    //.bind('conversationIncoming.cwic', methods.handleConversationIncoming)
                    ;
                $this.cwic('init', { 
                    encodeBase64:ciscobase.util.crypto.b64Encode,
                    verbose: true,
                    contactLookupJsonpHost: "",
                    ready:function(defaults,phoneRegistered, phoneMode) {
                        methods.phoneReadyCallback(defaults,phoneRegistered, phoneMode);
                    },
                    error: this.phoneErrorCallback,
                    log: function (msg, context) {
                        //console.trace();
                        if (typeof console !== "undefined" && console.log) {         
                            console.log(msg);
                            if (context) {
                                if(console.dir) {
                                    console.log(context);
                                } else if(typeof JSON !== "undefined" && JSON.stringify) {
                                    console.log(JSON.stringify(context,null,2));
                                } else {
                                    console.log(context);
                                }
                            }
                        };
                    }
                }); // Init
                return this;
            },
            createVideoWindow: function(videoid){
                if (!ws._videoObject){
                    w('#remotevideocontainer').cwic('createVideoWindow',{
                        id: (videoid)?videoid:'videoobject',
                        success: function(pluginid) {
                            //alert("Plugin OK: "+pluginid);
                            console.log("==========> #remotevideocontainer -> Video Object OK");
                            ws._videoObject = document.getElementById(pluginid);
                            if (delayedVideoConversation) {
                                // The update for the conversation that video is ready can occur before the createVideoWindow() call  
                                // returns asynchronously on some browsers, especially on Safari and background tabs.  Add the video 
                                // window to the call now.
                                w("#videocontainer, .videocontainer").show();
                                methods.getCallDiv(delayedVideoConversation.callId).cwic('updateConversation',{'addRemoteVideoWindow':ws._videoObject});
                                delayedVideoConversation = null;
                            } 
                        }
                    });
                }else{
                    console.log("==========>> WARNING: Video Object Already creadited");
                }
                return this;
            }

        }; // end of methods

        
        return methods;
    };// wJabber function
 
    w(document).ready(function(){
        tawags = w("#phonecontainer").wJabber();
        tawags.__init();//.call(null);
        console.log("wDocument Ready");
        w("#tap_postpaid").click(function(){
            console.log("Click----------");
        });
        w("#logout").click(function(){
            console.log("LogOut Click");
            //tawags.logout();
        });
        w("#login").click(function(){
            console.log("Click Login");
            //tawags = w("#phonecontainer").wJabber();
            tawags.__init();
            
        });
        w("#call").click(function(){
//            tawags = w("#phonecontainer").wJabber();
//            console.log("Call Click");
//            //  End call
//            tawags.setParticipant("6969").call(null);
        if (tawags.isPhoneRegistered()){
            //gwd.actions.gwdPagedeck.goToPage('pagedeck', 'video', 'fade', 500, 'ease-in-out', 'top');
            if (tawags.createVideoWindow('videoobject')){
                //tawags.setParticipant("6969");
                tawags.call(tawags.isPhoneRegistered());
            }
        }else{
            console.log("=======>> Phone working to register please try in moment");
        }

        });
        w("#endcall").click(function(){
            //  End call
            console.log("End Call Click");
            //tawags.endCall();
        });
        
//        document.addEventListener("unload", function(){
//            tawags.endCall();
//        });
    });
//    document.addEventListener("unload", function(evt){
//        tawags.endCall();
//        return "Seriously???";
//    });
//    window.addEventListener("unload", function(evt){
//        tawags.endCall();
//        return "Seriously???";
//    });
//
//    window.onbeforeunload = function(evt) {
//        tawags.endCall().logout();
//        return "REALLY?";
//    };

} (jQuery));

